package org.infosec.lc.exercises.apacheDigester;

import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.exolab.castor.xml.Marshaller;
import org.infosec.lc.exercises.apacheDigester.modle.Academy;

/**
 * 文件名：DigesterMain.java 作 者：林超 时 间：2011-7-15上午09:48:29
 * 
 * 功能描述：Digester主要是将XML文件转换为JavaBean 其中XML文件要符合digester-rules.dtd
 * 
 * pom.xml : <dependency> <groupId>commons-digester</groupId>
 * <artifactId>commons-digester</artifactId> <version>1.8</version>
 * </dependency>
 */
public class DigesterMain {

	URL rules;
	URL input;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DigesterMain digester = new DigesterMain();
		digester.digest();
	}
	
	@SuppressWarnings("unchecked")
	public void digest() {
		
		rules = this.getClass().getClassLoader().getResource("academyRules.xml");
		input = this.getClass().getClassLoader().getResource("academy.xml");
		
		try {
			checkURL(rules,input);
			
			// Create Digester using rules defined in academyRules.xml
			Digester digester = DigesterLoader.createDigester(rules);
			// Parse academy.xml using the Digester to get an instance of
			// Academy
			Academy a = (Academy) digester.parse(input);
			Vector vStud = a.getStudents();
			Vector vTeach = a.getTeachers();
			
			for (int i = 0; i < vStud.size(); i++) {
				System.out.println("Student>> "
						+ PropertyUtils.describe(vStud.get(i)));
			}
			for (int i = 0; i < vTeach.size(); i++) {
				System.out.println("Teacher>> "
						+ PropertyUtils.describe(vTeach.get(i)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void checkURL(URL rules,URL input)throws MalformedURLException{
		
		if(rules == null)
			this.rules = new URL("file:/"+new File("configs/academyRules.xml").getAbsolutePath());
		if(input == null)
			this.input = new URL("file:/"+new File("configs/academy.xml").getAbsolutePath());
	}

}
